package com.yjf.ljr.activity;

import java.text.DecimalFormat;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.yjf.ljr.R;
import com.yjf.ljr.adapter.CommonAdapter.HandleCallBack;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.connection.IjConnect;
import com.yjf.ljr.dataclass.AppinvestDataClass;
import com.yjf.ljr.dataclass.GetCheckCodeClass;
import com.yjf.ljr.dataclass.InvestUserRedPacketDataClass;
import com.yjf.ljr.dataclass.MyInvestClass;
import com.yjf.ljr.dataclass.MyInvestDataClass;
import com.yjf.ljr.dataclass.MyInvestDataClass.MyInvestDate;
import com.yjf.ljr.dataclass.RedPacketDataClass.RedPacketInfo;
import com.yjf.ljr.parser.RequestBuilder;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.util.AppInvestDialog;
import com.yjf.ljr.util.AppUtil;
import com.yjf.ljr.util.SPreferences;
import com.yjf.ljr.util.ViewCodeDialog;
import com.yjf.ljr.view.InvestDialog;
import com.yjf.ljr.view.RedPacketDialog;

public class MyInvestActivity extends IjActivity implements OnClickListener {
	@ID("tvavailablebalance")
	private TextView mTvAvailableBalance;// 可用余额
	@ID("tvesidualamount")
	private TextView mTvResidualAmount;// 剩余金额
	@ID("tvexpectedtotal")
	private TextView mTvExpectedTotal;// 预期总收益
	@ID("tvfirstInvestmentamount")
	private TextView mTvFirstInvestMentMoney;// 起投金额
	@ID("tvIncreaseInvestmentamount")
	// 递增金额
	private TextView mTvIncreaseInvestmentamount;
	@ID("etinvestmentmoney")
	private EditText mEtInvestmentMoney;// 投资金额
	@ID("ckagreen")
	private CheckBox mCkAgreen;// 同意
	@ID("btinverst")
	private Button mBtInverst;// 投资
	@ID("btadd")
	private Button mBtAdd;// 加
	@ID("btsubtract")
	private Button mBtSubtract;// 减
	@ID("fail_myinvest")
	private LinearLayout mLlfail_myinvest;//
	@ID("llmyinvest")
	private LinearLayout mLlmyinvest;//

	@ID("scroll_container")
	private ScrollView scrollContainer;
	@ID("red_packet_use_limit")
	private TextView redPacketUseAmountLimit;// 可使用的红包限额
	@ID("red_packet_amount_input")
	private EditText redPacketAmountInput;// 使用红包
	@ID("red_packet_total_amount")
	private TextView redPacketTotalAmount;// 红包总金额
	@ID("red_packet_container")
	private LinearLayout redPacketContainer;
	@ID("experience_container")
	private LinearLayout experienceContainer;
	@ID("experience_use_limit")
	private TextView experienceUseAmountLimit;// 可使用的体验金限额
	@ID("experience_amount_input")
	private EditText experienceAmountInput;// 使用体验
	@ID("experience_total_amount")
	private TextView experienceTotalAmount;// 体验金总金额

	@ID("experience_use_limit_container")
	private LinearLayout experienceUseLimitContainer;// 体验金使用限制容器
	@ID("red_packet_use_limit_container")
	private LinearLayout redPacketUseLimitContainer;// 红包使用限制容器

	private String IncreaseInvestmentamount;
	private double investmentamount;
	double temp_ResidualAmount;// 投资金额

	private WebView mNewWebView;
	private String token;// 校验码
	private String mCaptcha;// 验证码
	private String tradeId;// 当前项目的tradeID
	private String yearRate = "";// 年利化率
	private String timeLimit = "";// 期限
	private String codeinvest = "";// 验证码
	private String demandId;// 项目Id
	private String interestRate;// 年利化率
	private String yjfPaypassUrl;// 支付url
	private String mobile;
	private InvestDialog.Builder mBuilder;
	public static MyInvestActivity instance;
	public static boolean mDialogFlag = false;

	public String availableMoney = "";// 当前登录用户账户可用余额
	public String residueMoney = ""; // 当前项目剩余可投金额
	public String startMoney = "";// 起投金额

	public RedPacketDialog redPacketDialog;
	public InvestUserRedPacketDataClass investUserRedPacketData;
	private double lastInvestAmount;
	private boolean isInputInvestmentMoneyFinished = false;
	private String gainMoneyTradeIds;// 加息券查询ID
	@ID("llGainMoney")
	private LinearLayout mLlllGainMoney;// 是否使用加息券
	private String newerInvest;
	private int mSelect = -1;
	private String interestRateCoupon;// 加息券利率
	private double interestRateCouponD;// 加息券利率
	private String gainCanUsestr;// 当前投资可使用加息券上限
	private double gainCanUseD;// 当前投资可使用加息券上限
	private double interestRateCouponlast;// 加息券利率选择
	private static final int REQUEST_CODE_QUERYGIFTLIST = 3;
	private boolean isNewerInvest = false;// 是否是体验标
	@ID("tvrateOfYearuse")
	private TextView mTvrateOfYearuse;// 页面显示已选择的加息券百分比，
	private static final int REQUESTDETORRECHARGE = 1001;
	private Handler inputWatcher = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			double investAmount = AppUtil.moneyToNum(mEtInvestmentMoney.getText().toString().trim());
			getUserRedPacketMessage(demandId, investAmount);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_myinvest);
		isNewerInvest = false;// 默认不是体验标
		Intent intent = getIntent();
		tradeId = intent.getStringExtra("tradeId");
		demandId = getIntent().getStringExtra("demandId");
		interestRate = getIntent().getStringExtra("interestRate");
		timeLimit = getIntent().getStringExtra("timeLimit");
		new MyInvestActivityTask(demandId).execute();
		showProgressDialog();
		initControl();
	}

	private void initControl() {

		lastInvestAmount = -1.0d;

		setLeftBtnClick();
		setTitleStr("我要投资");
		instance = this;
		mLlllGainMoney.setOnClickListener(this);
		mLlllGainMoney.setVisibility(View.GONE);
		mBuilder = new InvestDialog.Builder(mContext);
		mBtSubtract.setOnClickListener(this);
		mBtAdd.setOnClickListener(this);
		mBtInverst.setOnClickListener(this);
		mEtInvestmentMoney.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable arg0) {

				calculateExpectedReturn();
				/*
				 * // TODO Auto-generated method stub
				 * 
				 * mTvResidualAmount;// 剩余金额 mTvExpectedTotal;// 预期总收益
				 * mTvFirstInvestMentMoney;// 起投金额
				 * 
				 * if
				 * (!(TextUtils.isEmpty(mEtInvestmentMoney.getText().toString(
				 * ))) &&
				 * (!TextUtils.isEmpty(mTvResidualAmount.getText().toString()))
				 * &&
				 * (!TextUtils.isEmpty(mTvFirstInvestMentMoney.getText().toString
				 * ())))
				 * 
				 * {
				 * 
				 * DecimalFormat df; double temp_totalmoeny;
				 * 
				 * DecimalFormat decimalFormatstring = new
				 * DecimalFormat(",###"); String temp_inver; String temp = "";
				 * String temp_string[]; double temp_InvestmentMoney; double
				 * temp_mincrease;// double temp_FirstInvestMentMoney;
				 * 
				 * String temp_inverInvestmentMoney; String temp_mIncrease;
				 * String temp_inverFirstInvestMentMoney;
				 * 
				 * String tempInvestmentMoney = ""; String
				 * tempFirstInvestMentMoney = ""; String tempIncrease = "";
				 * 
				 * String temp_stringInvestmentMoney[]; String
				 * temp_stringFirstInvestMentMoney[]; String
				 * temp_stringIncrease[]; temp_inverInvestmentMoney =
				 * mEtInvestmentMoney.getText().toString();
				 * temp_stringInvestmentMoney = new
				 * String[temp_inverInvestmentMoney.split(",").length];
				 * temp_stringInvestmentMoney =
				 * temp_inverInvestmentMoney.split(",");
				 * 
				 * for (int i = 0; i < temp_stringInvestmentMoney.length; i++) {
				 * tempInvestmentMoney = tempInvestmentMoney +
				 * temp_stringInvestmentMoney[i]; } temp_InvestmentMoney =
				 * Double.parseDouble(tempInvestmentMoney); String asa =
				 * mTvFirstInvestMentMoney.getText().toString();
				 * temp_inverFirstInvestMentMoney =
				 * mTvFirstInvestMentMoney.getText().toString() .substring(5,
				 * mTvFirstInvestMentMoney.getText().toString().length() - 2);
				 * String aa = temp_inverFirstInvestMentMoney;
				 * temp_stringFirstInvestMentMoney = new
				 * String[temp_inverFirstInvestMentMoney.split(",").length];
				 * temp_stringFirstInvestMentMoney =
				 * temp_inverFirstInvestMentMoney.split(",");
				 * 
				 * for (int i = 0; i < temp_stringFirstInvestMentMoney.length;
				 * i++) { tempFirstInvestMentMoney = tempFirstInvestMentMoney +
				 * temp_stringFirstInvestMentMoney[i]; }
				 * temp_FirstInvestMentMoney =
				 * Double.parseDouble(tempFirstInvestMentMoney);// 起投金额
				 *//****/
				/*
				 * 
				 * temp_inver = mEtInvestmentMoney.getText().toString();
				 * temp_string = new String[temp_inver.split(",").length];
				 * temp_string = temp_inver.split(",");
				 * 
				 * for (int i = 0; i < temp_string.length; i++) { temp = temp +
				 * temp_string[i]; } temp_totalmoeny = Double.parseDouble(temp);
				 * if (temp_ResidualAmount < temp_FirstInvestMentMoney) {
				 * mEtInvestmentMoney.setText(temp_ResidualAmount + ""); }
				 * 
				 * String yearRatae = yearRate + ""; String yeartimeLimit =
				 * timeLimit + ""; if
				 * (TextUtils.isEmpty(mEtInvestmentMoney.getText().toString()))
				 * { mTvExpectedTotal.setText("预期总收益 ￥" + "0" + "元"); } else {
				 * 
				 * 
				 * String yeartimeLt = (temp_totalmoeny *
				 * (Double.parseDouble(yearRate) * 0.01) * Double
				 * .parseDouble(timeLimit)) / 365 + "";
				 * 
				 * df = new DecimalFormat("#####0.00"); if
				 * ("月".equals(timeLimit.substring(timeLimit.length() - 1,
				 * timeLimit.length()))) { mTvExpectedTotal.setText("预期总收益 ￥" +
				 * df.format(((temp_totalmoeny * (Double.parseDouble(yearRate) *
				 * 0.01) * Double .parseDouble(timeLimit.substring(0,
				 * timeLimit.length() - 2)))) / 12) + "元");
				 * SpannableStringBuilder style = new
				 * SpannableStringBuilder(mTvExpectedTotal.getText()
				 * .toString()); style.setSpan(new
				 * ForegroundColorSpan(0xffef8613), 6,
				 * mTvExpectedTotal.getText().toString() .length() - 1,
				 * Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				 * mTvExpectedTotal.setText(style); // timeLimit = //
				 * Integer.parseInt((timeLimit.substring(0, //
				 * timeLimit.length() - 2))) * 30 + ""; } else if
				 * ("天".equals(timeLimit.substring(timeLimit.length() - 1,
				 * timeLimit.length()))) { mTvExpectedTotal.setText("预期总收益 ￥" +
				 * df.format(((temp_totalmoeny * (Double.parseDouble(yearRate) *
				 * 0.01) * Double .parseDouble(timeLimit.substring(0,
				 * timeLimit.length() - 1)))) / 360) + "元");
				 * SpannableStringBuilder style = new
				 * SpannableStringBuilder(mTvExpectedTotal.getText()
				 * .toString()); style.setSpan(new
				 * ForegroundColorSpan(0xffef8613), 6,
				 * mTvExpectedTotal.getText().toString() .length() - 1,
				 * Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				 * mTvExpectedTotal.setText(style); // timeLimit =
				 * timeLimit.substring(0, // timeLimit.length() - 1); }
				 * 
				 * mTvExpectedTotal.setText("预期总收益 ￥" +
				 * df.format(((temp_totalmoeny * (Double.parseDouble(yearRate) *
				 * 0.01) * Double .parseDouble(timeLimit))) / 365) + "" + "0" +
				 * "元");
				 * 
				 * }
				 * 
				 * SpannableStringBuilder style = new SpannableStringBuilder(
				 * mTvExpectedTotal.getText().toString()); style.setSpan(new
				 * ForegroundColorSpan(0xffef8613), 6,
				 * mTvExpectedTotal.getText().toString() .length() - 1,
				 * Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				 * 
				 * mTvExpectedTotal.setText(style);
				 * 
				 * 
				 * } else { mTvExpectedTotal.setText("预期总收益 ￥" + "0.00" + "元");
				 * SpannableStringBuilder style = new
				 * SpannableStringBuilder(mTvExpectedTotal
				 * .getText().toString()); style.setSpan(new
				 * ForegroundColorSpan(0xffef8613), 6,
				 * mTvExpectedTotal.getText().toString() .length() - 1,
				 * Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				 * 
				 * mTvExpectedTotal.setText(style); }
				 * 
				 * inputWatcher.removeMessages(0);
				 * inputWatcher.sendEmptyMessageDelayed(0, 1 * 1000);
				 */}
		});

		redPacketAmountInput.setFilters(new InputFilter[] { new DotFilter() });
		experienceAmountInput.setFilters(new InputFilter[] { new DotFilter() });
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		DecimalFormat df;
		double temp_totalmoeny;

		DecimalFormat decimalFormatstring = new DecimalFormat(",###");
		String temp_inver;
		String temp = "";
		String temp_string[];
		double temp_InvestmentMoney;
		double temp_mincrease;//
		double temp_FirstInvestMentMoney;

		String temp_inverInvestmentMoney;
		String temp_mIncrease;
		String temp_inverFirstInvestMentMoney;

		String tempInvestmentMoney = "";
		String tempFirstInvestMentMoney = "";
		String tempIncrease = "";

		String temp_stringInvestmentMoney[];
		String temp_stringFirstInvestMentMoney[];
		String temp_stringIncrease[];
		switch (view.getId()) {

		case R.id.btadd:

			/*
			 * mTvResidualAmount;// 剩余金额 mTvFirstInvestMentMoney;// 起投金额
			 * mEtInvestmentMoney;// 投资金额
			 */
			temp_inverInvestmentMoney = mEtInvestmentMoney.getText().toString();
			temp_stringInvestmentMoney = new String[temp_inverInvestmentMoney.split(",").length];
			temp_stringInvestmentMoney = temp_inverInvestmentMoney.split(",");

			for (int i = 0; i < temp_stringInvestmentMoney.length; i++) {
				tempInvestmentMoney = tempInvestmentMoney + temp_stringInvestmentMoney[i];
			}
			temp_InvestmentMoney = Double.parseDouble(tempInvestmentMoney);

			temp_inverFirstInvestMentMoney = mTvFirstInvestMentMoney.getText().toString()
					.substring(5, mTvFirstInvestMentMoney.getText().toString().length() - 2);
			temp_stringFirstInvestMentMoney = new String[temp_inverFirstInvestMentMoney.split(",").length];
			temp_stringFirstInvestMentMoney = temp_inverFirstInvestMentMoney.split(",");

			for (int i = 0; i < temp_stringFirstInvestMentMoney.length; i++) {
				tempFirstInvestMentMoney = tempFirstInvestMentMoney + temp_stringFirstInvestMentMoney[i];
			}
			temp_FirstInvestMentMoney = Double.parseDouble(tempFirstInvestMentMoney);
			/****/
			temp_mIncrease = mTvIncreaseInvestmentamount.getText().toString()
					.substring(5, mTvIncreaseInvestmentamount.getText().toString().length() - 1);
			temp_stringIncrease = new String[temp_mIncrease.split(",").length];
			temp_stringIncrease = temp_mIncrease.split(",");

			for (int i = 0; i < temp_stringIncrease.length; i++) {
				tempIncrease = tempIncrease + temp_stringIncrease[i];
			}
			temp_mincrease = Double.parseDouble(tempIncrease);
			/***/
			if ((temp_InvestmentMoney + temp_mincrease) > temp_ResidualAmount) {
				mBtAdd.setClickable(false);
				mBtSubtract.setClickable(true);
				if (temp_InvestmentMoney < temp_ResidualAmount) {
					Double investAmount = temp_ResidualAmount;
					df = new DecimalFormat("#####0.00");
					if ("月".equals(timeLimit.substring(timeLimit.length() - 1, timeLimit.length()))) {
						mTvExpectedTotal.setText("预期总收益 ￥"
								+ df.format(((investAmount * (Double.parseDouble(yearRate) * 0.01) * Double
										.parseDouble(timeLimit.substring(0, timeLimit.length() - 2)))) / 12) + "元");
						SpannableStringBuilder style = new SpannableStringBuilder(mTvExpectedTotal.getText().toString());
						style.setSpan(new ForegroundColorSpan(0xffef8613), 6, mTvExpectedTotal.getText().toString()
								.length() - 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
						mTvExpectedTotal.setText(style);
						// timeLimit = Integer.parseInt((timeLimit.substring(0,
						// timeLimit.length() - 2))) * 30 + "";
					} else if ("天".equals(timeLimit.substring(timeLimit.length() - 1, timeLimit.length()))) {
						mTvExpectedTotal.setText("预期总收益 ￥"
								+ df.format(((investAmount * (Double.parseDouble(yearRate) * 0.01) * Double
										.parseDouble(timeLimit.substring(0, timeLimit.length() - 1)))) / 360) + "元");
						SpannableStringBuilder style = new SpannableStringBuilder(mTvExpectedTotal.getText().toString());
						style.setSpan(new ForegroundColorSpan(0xffef8613), 6, mTvExpectedTotal.getText().toString()
								.length() - 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
						mTvExpectedTotal.setText(style);
					}
					mEtInvestmentMoney.setText(decimalFormatstring.format(investAmount) + ".00");
					getUserRedPacketMessage(demandId, investAmount);
				}
				return;

			}
			mBtSubtract.setClickable(true);
			temp_inver = mEtInvestmentMoney.getText().toString();
			temp_string = new String[temp_inver.split(",").length];
			temp_string = temp_inver.split(",");

			for (int i = 0; i < temp_string.length; i++) {
				temp = temp + temp_string[i];
			}
			temp_totalmoeny = Double.parseDouble(temp);
			if (IncreaseInvestmentamount != null) {
				investmentamount = Double.parseDouble(IncreaseInvestmentamount);
			} else {
				return;
			}
			temp_totalmoeny += investmentamount;

			df = new DecimalFormat("#####0.00");

			/***/

			if ("月".equals(timeLimit.substring(timeLimit.length() - 1, timeLimit.length()))) {
				mTvExpectedTotal.setText("预期总收益 ￥"
						+ df.format(((temp_totalmoeny * (Double.parseDouble(yearRate) * 0.01) * Double
								.parseDouble(timeLimit.substring(0, timeLimit.length() - 2)))) / 12) + "元");
				SpannableStringBuilder style = new SpannableStringBuilder(mTvExpectedTotal.getText().toString());
				style.setSpan(new ForegroundColorSpan(0xffef8613), 6,
						mTvExpectedTotal.getText().toString().length() - 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				mTvExpectedTotal.setText(style);
				// timeLimit = Integer.parseInt((timeLimit.substring(0,
				// timeLimit.length() - 2))) * 30 + "";
			} else if ("天".equals(timeLimit.substring(timeLimit.length() - 1, timeLimit.length()))) {
				mTvExpectedTotal.setText("预期总收益 ￥"
						+ df.format(((temp_totalmoeny * (Double.parseDouble(yearRate) * 0.01) * Double
								.parseDouble(timeLimit.substring(0, timeLimit.length() - 1)))) / 360) + "元");
				SpannableStringBuilder style = new SpannableStringBuilder(mTvExpectedTotal.getText().toString());
				style.setSpan(new ForegroundColorSpan(0xffef8613), 6,
						mTvExpectedTotal.getText().toString().length() - 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				mTvExpectedTotal.setText(style);
				// timeLimit = timeLimit.substring(0, timeLimit.length() - 1);
			}
			/***/
			/*
			 * mTvExpectedTotal.setText("预期总收益 ￥" + df.format(((temp_totalmoeny
			 * * (Double.parseDouble(yearRate) * 0.01) * Double
			 * .parseDouble(timeLimit))) / 365) + "" + "0" + "元");
			 * 
			 * SpannableStringBuilder style = new
			 * SpannableStringBuilder(mTvExpectedTotal.getText().toString());
			 * style.setSpan(new ForegroundColorSpan(0xffef8613), 6,
			 * mTvExpectedTotal.getText().toString().length() - 1,
			 * Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			 * 
			 * mTvExpectedTotal.setText(style);
			 */mEtInvestmentMoney.setText(decimalFormatstring.format(temp_totalmoeny) + ".00");
			getUserRedPacketMessage(demandId, temp_totalmoeny);
			break;
		case R.id.btsubtract:

			/*
			 * mTvResidualAmount;// 剩余金额 mTvFirstInvestMentMoney;// 起投金额
			 * mEtInvestmentMoney;// 投资金额
			 */
			temp_inverInvestmentMoney = mEtInvestmentMoney.getText().toString();
			temp_stringInvestmentMoney = new String[temp_inverInvestmentMoney.split(",").length];
			temp_stringInvestmentMoney = temp_inverInvestmentMoney.split(",");

			for (int i = 0; i < temp_stringInvestmentMoney.length; i++) {
				tempInvestmentMoney = tempInvestmentMoney + temp_stringInvestmentMoney[i];
			}
			temp_InvestmentMoney = Double.parseDouble(tempInvestmentMoney);

			temp_inverFirstInvestMentMoney = mTvFirstInvestMentMoney.getText().toString()
					.substring(5, mTvFirstInvestMentMoney.getText().toString().length() - 2);
			temp_stringFirstInvestMentMoney = new String[temp_inverFirstInvestMentMoney.split(",").length];
			temp_stringFirstInvestMentMoney = temp_inverFirstInvestMentMoney.split(",");

			for (int i = 0; i < temp_stringFirstInvestMentMoney.length; i++) {
				tempFirstInvestMentMoney = tempFirstInvestMentMoney + temp_stringFirstInvestMentMoney[i];
			}
			/****/
			temp_mIncrease = mTvIncreaseInvestmentamount.getText().toString()
					.substring(5, mTvIncreaseInvestmentamount.getText().toString().length() - 1);
			temp_stringIncrease = new String[temp_mIncrease.split(",").length];
			temp_stringIncrease = temp_mIncrease.split(",");

			for (int i = 0; i < temp_stringIncrease.length; i++) {
				tempIncrease = tempIncrease + temp_stringIncrease[i];
			}
			temp_mincrease = Double.parseDouble(tempIncrease);
			/***/
			temp_FirstInvestMentMoney = Double.parseDouble(tempFirstInvestMentMoney);
			if ((temp_InvestmentMoney - temp_mincrease) < temp_FirstInvestMentMoney) {
				mBtSubtract.setClickable(false);
				mBtAdd.setClickable(true);
				return;

			}
			mBtAdd.setClickable(true);
			temp_inver = mEtInvestmentMoney.getText().toString();
			temp_string = new String[temp_inver.split(",").length];
			temp_string = temp_inver.split(",");

			for (int i = 0; i < temp_string.length; i++) {
				temp = temp + temp_string[i];
			}
			temp_totalmoeny = Double.parseDouble(temp);
			if (IncreaseInvestmentamount != null) {
				investmentamount = Double.parseDouble(IncreaseInvestmentamount);
			} else {
				return;
			}
			if (temp_totalmoeny - investmentamount > 0) {
				temp_totalmoeny -= investmentamount;
			} else {
				showToast("投资金额过低");
				return;
			}
			df = new DecimalFormat("#####0.00");

			/***/
			if ("月".equals(timeLimit.substring(timeLimit.length() - 1, timeLimit.length()))) {
				mTvExpectedTotal.setText("预期总收益 ￥"
						+ df.format(((temp_totalmoeny * (Double.parseDouble(yearRate) * 0.01) * Double
								.parseDouble(timeLimit.substring(0, timeLimit.length() - 2)))) / 12) + "元");
				SpannableStringBuilder style = new SpannableStringBuilder(mTvExpectedTotal.getText().toString());
				style.setSpan(new ForegroundColorSpan(0xffef8613), 6,
						mTvExpectedTotal.getText().toString().length() - 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				mTvExpectedTotal.setText(style);
				// timeLimit = Integer.parseInt((timeLimit.substring(0,
				// timeLimit.length() - 2))) * 30 + "";
			} else if ("天".equals(timeLimit.substring(timeLimit.length() - 1, timeLimit.length()))) {
				mTvExpectedTotal.setText("预期总收益 ￥"
						+ df.format(((temp_totalmoeny * (Double.parseDouble(yearRate) * 0.01) * Double
								.parseDouble(timeLimit.substring(0, timeLimit.length() - 1)))) / 360) + "元");
				SpannableStringBuilder style = new SpannableStringBuilder(mTvExpectedTotal.getText().toString());
				style.setSpan(new ForegroundColorSpan(0xffef8613), 6,
						mTvExpectedTotal.getText().toString().length() - 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				mTvExpectedTotal.setText(style);
				// timeLimit = timeLimit.substring(0, timeLimit.length() - 1);
			}
			/**/
			/*
			 * mTvExpectedTotal.setText("预期总收益 ￥" + df.format(((temp_totalmoeny
			 * * (Double.parseDouble(yearRate) * 0.01) * Double
			 * .parseDouble(timeLimit))) / 365) + "" + "0" + "元");
			 * SpannableStringBuilder style1 = new
			 * SpannableStringBuilder(mTvExpectedTotal.getText().toString());
			 * style1.setSpan(new ForegroundColorSpan(0xffef8613), 6,
			 * mTvExpectedTotal.getText().toString().length() - 1,
			 * Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			 * 
			 * mTvExpectedTotal.setText(style1);
			 */
			mEtInvestmentMoney.setText(decimalFormatstring.format(temp_totalmoeny) + ".00");
			getUserRedPacketMessage(demandId, temp_totalmoeny);
			break;
		case R.id.btinverst:
			/*
			 * if (mCkAgreen.isChecked()) { new GetCheckCodeTask().execute(); }
			 * else { showToast("没有同意投资协议"); }
			 */
			// new GetCheckCodeTask().execute();

			// add red packet and experience amount
			double redPacketUseAmount = AppUtil.moneyToNum(redPacketAmountInput.getText().toString().trim());
			double experienceUseAmount = AppUtil.moneyToNum(experienceAmountInput.getText().toString().trim());
			double giftMoneyLimitAmount = 0;
			double giftMoney = 0;
			double experienceLimitAmount = 0;
			double experienceAmount = 0;
			if (investUserRedPacketData != null) {
				giftMoneyLimitAmount = AppUtil.moneyToNum(investUserRedPacketData.giftMoneyLimitAmount);
				giftMoney = AppUtil.moneyToNum(investUserRedPacketData.giftMoney);
				experienceLimitAmount = AppUtil.moneyToNum(investUserRedPacketData.experienceLimitAmount);
				experienceAmount = AppUtil.moneyToNum(investUserRedPacketData.experienceAmount);
				if (!TextUtils.isEmpty(investUserRedPacketData.giftMoneyLimitAmount)
						&& redPacketUseAmount > giftMoneyLimitAmount) {
					showToast("红包金额不能大于项目可使用的红包金额！");
					return;
				} else if (redPacketUseAmount > giftMoney) {
					showToast("红包金额不能大于您当前红包总额！");
					return;
				} else {
					mBuilder.setGiftMoney(redPacketUseAmount + "");
				}
				if (!TextUtils.isEmpty(investUserRedPacketData.experienceLimitAmount)
						&& experienceUseAmount > experienceLimitAmount) {
					showToast("体验金不能大于项目可使用的体验金总额！");
					return;
				} else if (experienceUseAmount > experienceAmount) {
					showToast("体验金不能大于您当前体验金总额！");
					return;
				} else {
					mBuilder.setExperienceAmount(experienceUseAmount + "");
				}
				double discount = redPacketUseAmount + experienceUseAmount;
				double investAmountD = AppUtil.moneyToNum(mEtInvestmentMoney.getText().toString().trim());
				if (discount > investAmountD) {
					showToast("使用红包金额或体验金金额不能大于投资金额。");
					return;
				}
			} else {
				mBuilder.setGiftMoney("");
				mBuilder.setExperienceAmount("");
			}

			double realAvailableMoney = redPacketUseAmount + experienceUseAmount + AppUtil.moneyToNum(availableMoney);
			if (realAvailableMoney < Double.parseDouble(residueMoney.replace(",", ""))
					&& realAvailableMoney < Double.parseDouble(startMoney.replace(",", ""))) {
				// showToast("可用投资金额过低,无法进行投资。");
				if (!isNewerInvest) {
					new AlertDialog.Builder(MyInvestActivity.this).setMessage("可用投资金额过低,无法进行投资。").setTitle("提示")
							.setPositiveButton("立即充值", new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									startActivityForResult(new Intent(MyInvestActivity.this, RechargeActivity.class),
											REQUESTDETORRECHARGE);
								}
							}).setNegativeButton("暂不充值", new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub

								}
							}).create().show();
				} else {
					showToast("体验金不足，无法进行投资。");
				}
				return;
			}

			// if (Double.parseDouble(availableMoney.replace(",", "")) <
			// Double.parseDouble(residueMoney.replace(",", ""))
			// && Double.parseDouble(availableMoney.replace(",", "")) <
			// Double.parseDouble(startMoney.replace(",",
			// ""))) {
			// showToast("余额不足:无法进行投资。");
			// return;
			// }

			if (!(TextUtils.isEmpty(mEtInvestmentMoney.getText()))) {
				String temp_increase = mTvIncreaseInvestmentamount.getText().toString()
						.substring(5, mTvIncreaseInvestmentamount.getText().toString().length() - 1);
				String temp_investmentmoney = mEtInvestmentMoney.getText().toString().replace(",", "");
				double increase = Integer.parseInt(temp_increase);
				double investmentmoney = (Double.parseDouble(temp_investmentmoney));

				String temp_inverResidualAmount = mTvResidualAmount.getText().toString()
						.substring(7, mTvResidualAmount.getText().toString().length() - 1).replace(",", "");
				double inverResidualAmount = (Double.parseDouble(temp_inverResidualAmount));
				String temp_inverFirstMoney = mTvFirstInvestMentMoney.getText().toString()
						.substring(5, mTvFirstInvestMentMoney.getText().toString().length() - 2).replace(",", "");
				double inverFirstMoney = Double.parseDouble(temp_inverFirstMoney);
				if (investmentmoney > inverResidualAmount) {
					showToast("投资金额不能大于该笔借款的可投资金额");
					return;
				}
				if (inverResidualAmount > Double.parseDouble(startMoney.replace(",", ""))) {
					if (!(investmentmoney % increase == 0)) {
						// showToast("投资金额必须为1000.0元的整数倍");
						showToast("投资金额必须为" + increase + "元的整数倍");
						return;
					}
				}
				if (investmentmoney < inverFirstMoney && inverResidualAmount > investmentmoney) {
					showToast("投资金额不能小于起投金额");
					return;
				}

				if (realAvailableMoney < investmentmoney) {
					showToast("资金不足,无法进行投资!");
					return;
				}

				mBuilder.setIsNewerInvest(isNewerInvest);// 是否是体验标

				// getInvestCode(); // 投资短信验证码
				mBuilder.setPaypassUrl(yjfPaypassUrl);
				mBuilder.setAmount(investmentmoney + "");
				mBuilder.setToken(token);
				mBuilder.setDemandId(demandId);
				mBuilder.setTradeId(tradeId);
				mBuilder.setGiftTradeId(gainMoneyTradeIds);
				if(TextUtils.isEmpty(mobile)) {
					showToast("手机号码为空");
					return;
				}
				mBuilder.setmobile(mobile);
				mBuilder.setTitle("支付密码");
				mBuilder.create().show();
			} else {
				showToast("投资金额不能为空！！！");
			}
			break;
		case R.id.fail_myinvest:
			new MyInvestActivityTask(SPreferences.getData(mContext, "", "projectId").toString()).execute();
			showProgressDialog();
			break;
		case R.id.llGainMoney:// 加载加息券
			Intent intent = new Intent(mContext, QueryGiftListActivity.class);
			intent.putExtra("mSelect", mSelect);
			intent.putExtra("queryGiftPercent", gainCanUsestr);
			startActivityForResult(intent, REQUEST_CODE_QUERYGIFTLIST);
			break;

		default:
			break;
		}
	}

	class MyInvestActivityTask extends AsyncTask<Void, Void, Void> implements OnClickListener {
		private String demandId;// 项目ID
		private String mFailLog;
		private MyInvestDataClass date = new MyInvestDataClass();

		public MyInvestActivityTask(String demandId) {
			this.demandId = demandId;
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			RequestObject requestObjectSms = new RequestObject();
			requestObjectSms.method = "gotoInvest";
			requestObjectSms.map.put("demandId", demandId);

			String requestSmsUrl = RequestBuilder.build(requestObjectSms);
			try {
				IjConnect.doRequest(requestSmsUrl, date);
				if (date.code == null) {
					mFailLog = getResources().getString(R.string.loaddata_exception);
				} else if (!date.code.equals(CommonData.RESULT_SUCCESS)) {
					if (TextUtils.isEmpty(date.msg)) {
						mFailLog = getResources().getString(R.string.loaddata_exception);
					} else {
						mFailLog = date.msg;
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
				mFailLog = getResources().getString(R.string.loaddata_exception);
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			if ("-1".equals(date.code)) {
				loginWebview();
				return;
			}
			if (!TextUtils.isEmpty(mFailLog)) {
				mLlfail_myinvest.setVisibility(View.VISIBLE);
				mLlfail_myinvest.setOnClickListener(this);
				mLlmyinvest.setVisibility(View.GONE);
				scrollContainer.setVisibility(View.GONE);
				dismissProgressDialog();
				showToast(mFailLog);

			} else {

				showRedPacketAndExperience(null);

				mLlfail_myinvest.setVisibility(View.GONE);
				mLlmyinvest.setVisibility(View.VISIBLE);
				scrollContainer.setVisibility(View.VISIBLE);
				yearRate = interestRate;
				yearRate = yearRate.substring(0, yearRate.length() - 1);
				yjfPaypassUrl = date.yjfPaypassUrl;
				isNewerInvest = false;// 默认不是体验标
				MyInvestDate data = (MyInvestDate) date.getInvestInfo;
				if (date.code != null && date.code.equals(CommonData.RESULT_SUCCESS)) {
					// TODO GET Verification code
					token = data.token;
					mobile = data.mobile;
					IncreaseInvestmentamount = data.increaseAmount;
					String availableTip = "可用余额";
					// 是否是体验标
					if (!TextUtils.isEmpty(data.newerInvest) && data.newerInvest.equals("1")) {
						availableTip = "可用体验金";
						isNewerInvest = true;
					} else {
						isNewerInvest = false;
					}
					mTvAvailableBalance.setText(availableTip + "￥" + data.availableBalance + "元");// 可用余额
					SpannableStringBuilder style2 = new SpannableStringBuilder(mTvAvailableBalance.getText().toString());
					style2.setSpan(new ForegroundColorSpan(0xffef8613), availableTip.length()/* 4 */,
							mTvAvailableBalance.getText().toString().length() - 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
					if (Double.parseDouble(data.avalableAmount.replace(",", "")) < Double
							.parseDouble(data.leastInvestAmount.replace(",", ""))) {
						mEtInvestmentMoney.setText(data.avalableAmount);
					} else {
						mEtInvestmentMoney.setText(data.leastInvestAmount);
					}
					mTvAvailableBalance.setText(style2);
					mTvResidualAmount.setText("剩余可投资金额" + data.avalableAmount + "元");// 剩余金额
					mTvFirstInvestMentMoney.setText("起投金额：" + data.leastInvestAmount + "元 ");// 起投金额
					if (data.increaseAmount == null) {
						mTvIncreaseInvestmentamount.setText("递增金额：" + 0 + "元");// 递增金额
					} else {
						mTvIncreaseInvestmentamount.setText("递增金额：" + data.increaseAmount + "元");// 递增金额
					}
					SPreferences.saveData(mContext, data.viewMobile, "investphone");

					availableMoney = data.availableBalance;
					residueMoney = data.avalableAmount;
					startMoney = data.leastInvestAmount;

					// if (Double.parseDouble(data.availableBalance.replace(",",
					// "")) < Double
					// .parseDouble(data.avalableAmount.replace(",", ""))
					// && Double.parseDouble(data.availableBalance.replace(",",
					// "")) < Double
					// .parseDouble(data.leastInvestAmount.replace(",", ""))) {
					// showToast("余额不足:无法进行投资。");
					// mBtInverst.setBackgroundResource(R.drawable.shape_invertcancel);
					//
					// mBtInverst.setClickable(false);
					//
					// }
				}

				/************/

				double temp_FirstInvestMentMoney;
				String temp_inverResidualAmount;
				String temp_inverFirstInvestMentMoney;

				String tempResidualAmount = "";
				String tempFirstInvestMentMoney = "";

				String temp_stringResidualAmount[];
				String temp_stringFirstInvestMentMoney[];

				/*
				 * mTvResidualAmount;// 剩余金额 mTvFirstInvestMentMoney;// 起投金额
				 * mEtInvestmentMoney;// 投资金额
				 */
				temp_inverResidualAmount = mTvResidualAmount.getText().toString()
						.substring(7, mTvResidualAmount.getText().toString().length() - 1);
				temp_stringResidualAmount = new String[temp_inverResidualAmount.split(",").length];
				temp_stringResidualAmount = temp_inverResidualAmount.split(",");

				for (int i = 0; i < temp_stringResidualAmount.length; i++) {
					tempResidualAmount = tempResidualAmount + temp_stringResidualAmount[i];
				}
				temp_ResidualAmount = Double.parseDouble(tempResidualAmount);

				temp_inverFirstInvestMentMoney = mTvFirstInvestMentMoney.getText().toString()
						.substring(5, mTvFirstInvestMentMoney.getText().toString().length() - 2);
				temp_stringFirstInvestMentMoney = new String[temp_inverFirstInvestMentMoney.split(",").length];
				temp_stringFirstInvestMentMoney = temp_inverFirstInvestMentMoney.split(",");

				for (int i = 0; i < temp_stringFirstInvestMentMoney.length; i++) {
					tempFirstInvestMentMoney = tempFirstInvestMentMoney + temp_stringFirstInvestMentMoney[i];
				}
				temp_FirstInvestMentMoney = Double.parseDouble(tempFirstInvestMentMoney);
				if (temp_ResidualAmount < temp_FirstInvestMentMoney) {
					mBtAdd.setClickable(false);
					mBtSubtract.setClickable(false);
					mEtInvestmentMoney.setEnabled(false);
					/*
					 * String aa = mTvResidualAmount.getText().toString()
					 * .subSequence(7,
					 * mTvResidualAmount.getText().toString().length() - 1) +
					 * "";
					 * mEtInvestmentMoney.setText(mTvResidualAmount.getText()
					 * .toString() .subSequence(7,
					 * mTvResidualAmount.getText().toString().length() - 1) +
					 * "");
					 */

				}

				/*******************/

				double temp_totalmoeny;
				String temp_inver;
				String temp = "";
				String temp_string[];
				temp_inver = mEtInvestmentMoney.getText().toString();
				temp_string = new String[temp_inver.split(",").length];
				temp_string = temp_inver.split(",");
				for (int i = 0; i < temp_string.length; i++) {
					temp = temp + temp_string[i];
				}
				temp_totalmoeny = Double.parseDouble(temp);
				if (IncreaseInvestmentamount != null) {
					investmentamount = Double.parseDouble(IncreaseInvestmentamount);
				} else {
					dismissProgressDialog();
					return;
				}
				DecimalFormat df = new DecimalFormat("####0.00");
				String aaString = temp_totalmoeny + "";
				String aaStrisng = yearRate;
				String ss = timeLimit;

				if ("月".equals(timeLimit.substring(timeLimit.length() - 1, timeLimit.length()))) {
					mTvExpectedTotal.setText("预期总收益 ￥"
							+ df.format(((temp_totalmoeny * (Double.parseDouble(yearRate) * 0.01) * Double
									.parseDouble(timeLimit.substring(0, timeLimit.length() - 2)))) / 12) + "元");
					SpannableStringBuilder style = new SpannableStringBuilder(mTvExpectedTotal.getText().toString());
					style.setSpan(new ForegroundColorSpan(0xffef8613), 6, mTvExpectedTotal.getText().toString()
							.length() - 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
					mTvExpectedTotal.setText(style);
					// timeLimit = Integer.parseInt((timeLimit.substring(0,
					// timeLimit.length() - 2))) * 30 + "";
				} else if ("天".equals(timeLimit.substring(timeLimit.length() - 1, timeLimit.length()))) {
					mTvExpectedTotal.setText("预期总收益 ￥"
							+ df.format(((temp_totalmoeny * (Double.parseDouble(yearRate) * 0.01) * Double
									.parseDouble(timeLimit.substring(0, timeLimit.length() - 1)))) / 360) + "元");
					SpannableStringBuilder style = new SpannableStringBuilder(mTvExpectedTotal.getText().toString());
					style.setSpan(new ForegroundColorSpan(0xffef8613), 6, mTvExpectedTotal.getText().toString()
							.length() - 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
					mTvExpectedTotal.setText(style);
					// timeLimit = timeLimit.substring(0, timeLimit.length() -
					// 1);
				}
				getUserRedPacketMessage(demandId, temp_totalmoeny);
			}
			dismissProgressDialog();
		}

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			new MyInvestActivityTask(SPreferences.getData(mContext, "", "projectId").toString()).execute();
			showProgressDialog();
		}
	}

	private void refresh() {

		new MyInvestActivityTask(demandId).execute();
		showProgressDialog();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CommonData.REQUEST_CODE_LOGIN:
				// refresh();
				finish();
				break;
			case REQUEST_CODE_QUERYGIFTLIST:
				mSelect = intent.getIntExtra("mSelect", -1);
				if (TextUtils.isEmpty(intent.getStringExtra("rateOfYear"))) {
					mTvrateOfYearuse.setText("该项目可使用加息券");
					interestRateCouponlast = 0;
					interestRateCoupon = "";

				} else {
					interestRateCoupon = intent.getStringExtra("rateOfYear");
					try {
						gainCanUseD = Double.parseDouble(gainCanUsestr);
						interestRateCouponD = Double.parseDouble(interestRateCoupon);
						if (gainCanUseD > interestRateCouponD) {// 选择的加息券不高于上限
							mTvrateOfYearuse.setText("+" + interestRateCouponD + "%");
							interestRateCouponlast = interestRateCouponD;
						} else {// 选择的加息券高于上限
							mTvrateOfYearuse.setText("+" + gainCanUseD + "%");
							interestRateCouponlast = gainCanUseD;
						}

					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
				// 计算预期收益
				calculateExpectedReturn();
				gainMoneyTradeIds = intent.getStringExtra("giftTradeId");
				break;
			case REQUESTDETORRECHARGE:
				showProgressDialog();
				new MyInvestActivityTask(demandId).execute();
				break;
			default:
				break;
			}

		} else {
			if (REQUEST_CODE_QUERYGIFTLIST != requestCode) {
				finish();
			}
		}
		super.onActivityResult(requestCode, resultCode, intent);
	}

	// 计算预期收益
	private void calculateExpectedReturn() {

		// TODO Auto-generated method stub

		if (!(TextUtils.isEmpty(mEtInvestmentMoney.getText().toString()))
				&& (!TextUtils.isEmpty(mTvResidualAmount.getText().toString()))
				&& (!TextUtils.isEmpty(mTvFirstInvestMentMoney.getText().toString())))

		{

			DecimalFormat df;
			double temp_totalmoeny;

			String temp_inver;
			String temp = "";
			String temp_string[];
			double temp_FirstInvestMentMoney;

			String temp_inverInvestmentMoney;
			String temp_inverFirstInvestMentMoney;

			String tempInvestmentMoney = "";
			String tempFirstInvestMentMoney = "";

			String temp_stringInvestmentMoney[];
			String temp_stringFirstInvestMentMoney[];
			temp_inverInvestmentMoney = mEtInvestmentMoney.getText().toString();
			temp_stringInvestmentMoney = new String[temp_inverInvestmentMoney.split(",").length];
			temp_stringInvestmentMoney = temp_inverInvestmentMoney.split(",");

			for (int i = 0; i < temp_stringInvestmentMoney.length; i++) {
				tempInvestmentMoney = tempInvestmentMoney + temp_stringInvestmentMoney[i];
			}
			temp_inverFirstInvestMentMoney = mTvFirstInvestMentMoney.getText().toString()
					.substring(5, mTvFirstInvestMentMoney.getText().toString().length() - 2);
			temp_stringFirstInvestMentMoney = new String[temp_inverFirstInvestMentMoney.split(",").length];
			temp_stringFirstInvestMentMoney = temp_inverFirstInvestMentMoney.split(",");

			for (int i = 0; i < temp_stringFirstInvestMentMoney.length; i++) {
				tempFirstInvestMentMoney = tempFirstInvestMentMoney + temp_stringFirstInvestMentMoney[i];
			}
			temp_FirstInvestMentMoney = Double.parseDouble(tempFirstInvestMentMoney);// 起投金额
			/****/

			temp_inver = mEtInvestmentMoney.getText().toString();
			temp_string = new String[temp_inver.split(",").length];
			temp_string = temp_inver.split(",");

			for (int i = 0; i < temp_string.length; i++) {
				temp = temp + temp_string[i];
			}
			temp_totalmoeny = Double.parseDouble(temp);
			if (temp_ResidualAmount < temp_FirstInvestMentMoney) {
				mEtInvestmentMoney.setText(temp_ResidualAmount + "");
			}

			if (TextUtils.isEmpty(mEtInvestmentMoney.getText().toString())) {
				mTvExpectedTotal.setText("预期总收益 " + "0" + "元");
			} else {
				try {
					df = new DecimalFormat("#####0.00");
					if ("月".equals(timeLimit.substring(timeLimit.length() - 1, timeLimit.length()))) {
						if (interestRateCouponlast != 0) {

							mTvExpectedTotal.setText("预期总收益 "
									+ df.format(((temp_totalmoeny * (Double.parseDouble(yearRate) * 0.01) * Double
											.parseDouble(timeLimit.substring(0, timeLimit.length() - 2)))) / 12)
									+ "+"
									+ df.format(((temp_totalmoeny * (interestRateCouponlast * 0.01) * Double
											.parseDouble(timeLimit.substring(0, timeLimit.length() - 2)))) / 12) + "元");
							SpannableStringBuilder style = new SpannableStringBuilder(mTvExpectedTotal.getText()
									.toString());
							style.setSpan(new ForegroundColorSpan(0xffff6600), 5, mTvExpectedTotal.getText().toString()
									.length() - 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
							mTvExpectedTotal.setText(style);

						} else {

							mTvExpectedTotal.setText("预期总收益 "
									+ df.format(((temp_totalmoeny * (Double.parseDouble(yearRate) * 0.01) * Double
											.parseDouble(timeLimit.substring(0, timeLimit.length() - 2)))) / 12) + "元");
							SpannableStringBuilder style = new SpannableStringBuilder(mTvExpectedTotal.getText()
									.toString());
							style.setSpan(new ForegroundColorSpan(0xffff6600), 5, mTvExpectedTotal.getText().toString()
									.length() - 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
							mTvExpectedTotal.setText(style);

						}
					} else if ("天".equals(timeLimit.substring(timeLimit.length() - 1, timeLimit.length()))) {
						if (interestRateCouponlast != 0) {
							mTvExpectedTotal
									.setText("预期总收益 "
											+ df.format(((temp_totalmoeny * (Double.parseDouble(yearRate) * 0.01) * Double
													.parseDouble(timeLimit.substring(0, timeLimit.length() - 1)))) / 360)
											+ "+"
											+ df.format(((temp_totalmoeny * (interestRateCouponlast * 0.01) * Double
													.parseDouble(timeLimit.substring(0, timeLimit.length() - 1)))) / 360)
											+ "元");
							SpannableStringBuilder style = new SpannableStringBuilder(mTvExpectedTotal.getText()
									.toString());
							style.setSpan(new ForegroundColorSpan(0xffff6600), 5, mTvExpectedTotal.getText().toString()
									.length() - 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
							mTvExpectedTotal.setText(style);

						} else {
							mTvExpectedTotal
									.setText("预期总收益 "
											+ df.format(((temp_totalmoeny * (Double.parseDouble(yearRate) * 0.01) * Double
													.parseDouble(timeLimit.substring(0, timeLimit.length() - 1)))) / 360)
											+ "元");
							SpannableStringBuilder style = new SpannableStringBuilder(mTvExpectedTotal.getText()
									.toString());
							style.setSpan(new ForegroundColorSpan(0xffff6600), 5, mTvExpectedTotal.getText().toString()
									.length() - 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
							mTvExpectedTotal.setText(style);

						}
					}
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		} else {
			mTvExpectedTotal.setText("预期总收益 " + "0.00" + "元");
			SpannableStringBuilder style = new SpannableStringBuilder(mTvExpectedTotal.getText().toString());
			style.setSpan(new ForegroundColorSpan(0xffff6600), 5, mTvExpectedTotal.getText().toString().length() - 1,
					Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

			mTvExpectedTotal.setText(style);
		}

		inputWatcher.removeMessages(0);
		inputWatcher.sendEmptyMessageDelayed(0, 1 * 1000);

	}

	/*********** 获取投资验证码 ******/
	private void getInvestCode() {
		final ViewCodeDialog.Builder mBuilder = new ViewCodeDialog.Builder(mContext);
		mBuilder.setTitle("验证码");
		// mBuilder.setViewcode(data);
		// mBuilder.setInverseBackgroundForced(true);
		mBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				// TODO Auto-generated method stub
				if (TextUtils.isEmpty(mBuilder.getViewCode())) {
					showToast("请输入验证码");
					return;
				} else {
					dialog.dismiss();
					String investmentMoney[] = new String[mEtInvestmentMoney.getText().toString().split(",").length];
					String temp_invest = "";
					mCaptcha = mBuilder.getViewCode();
					investmentMoney = mEtInvestmentMoney.getText().toString().split(",");
					for (int i = 0; i < investmentMoney.length; i++) {
						temp_invest += investmentMoney[i];
					}

					new MyInvestTask(tradeId, token, mCaptcha, temp_invest, SPreferences.getData(mContext, "",
							"projectId").toString(), mBuilder.getViewCode()).execute();
					showProgressDialog();
				}
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		}).reFresh(null, mContext, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
			}
		});
		mBuilder.create().show();

	}

	/** 获取captcha校验码 **/

	class GetCheckCodeTask extends AsyncTask<Void, Void, Void> {

		String sessionCookie;
		CookieManager cookieManager;

		private String mFailLog;
		private GetCheckCodeClass data = new GetCheckCodeClass();

		@Override
		protected void onPreExecute() {

			CookieSyncManager.createInstance(MyInvestActivity.this);
			cookieManager = CookieManager.getInstance();

			sessionCookie = CommonData.SESSIONID;
			if (sessionCookie != null) {
				// delete old cookies
				cookieManager.removeSessionCookie();
			}
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			RequestObject requestObject = new RequestObject();
			requestObject.method = "getCheckCode";
			String requestUrl = RequestBuilder.build(requestObject);

			try {
				IjConnect.doRequest(requestUrl, data);

				if (data.code != null) {
					mFailLog = getResources().getString(R.string.loaddata_exception);
				}
			} catch (Exception e) {
				mFailLog = getResources().getString(R.string.loaddata_exception);
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (!TextUtils.isEmpty(mFailLog)) { // showToast(mFailLog);
				showToast(mFailLog);
			} else {

				// mWebView.loadUrl("http://192.168.45.212:28000/app/getCheckCode.htm");

				final ViewCodeDialog.Builder mBuilder = new ViewCodeDialog.Builder(mContext);
				mBuilder.setTitle("验证码");
				// mBuilder.setViewcode(data);
				// mBuilder.setInverseBackgroundForced(true);
				mBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						// TODO Auto-generated method stub
						if (TextUtils.isEmpty(mBuilder.getViewCode())) {
							showToast("请输入验证码");
							return;
						} else {
							dialog.dismiss();
							String investmentMoney[] = new String[mEtInvestmentMoney.getText().toString().split(",").length];
							String temp_invest = "";
							mCaptcha = mBuilder.getViewCode();
							investmentMoney = mEtInvestmentMoney.getText().toString().split(",");
							for (int i = 0; i < investmentMoney.length; i++) {
								temp_invest += investmentMoney[i];
							}

							new MyInvestTask(tradeId, token, mCaptcha, temp_invest, SPreferences.getData(mContext, "",
									"projectId").toString(), mBuilder.getViewCode()).execute();
							showProgressDialog();
						}
					}
				}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				}).reFresh(null, mContext, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
					}
				});
				mBuilder.create().show();

			}
		}
	}

	/**
	 * 我要投资
	 * 
	 * @author haiyang
	 * 
	 */
	class MyInvestTask extends AsyncTask<Void, Void, Void> {
		private String tradeId;
		private String token;
		private String captcha;
		private String amount;
		private String mFailLog;
		private String projectId;
		private String code;
		private MyInvestClass data = new MyInvestClass();

		public MyInvestTask(String tradeId, String token, String mCaptcha, String mAmount, String projectId, String code) {
			this.tradeId = tradeId;
			this.token = token;
			this.captcha = mCaptcha;
			this.amount = mAmount;
			this.projectId = projectId;
			this.code = code;

		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			RequestObject requestObject = new RequestObject();
			requestObject.method = "appInvest";

			requestObject.map.put("tradeId", tradeId);
			requestObject.map.put("token", token);
			requestObject.map.put("captcha", mCaptcha);
			requestObject.map.put("amount", amount);
			requestObject.map.put("projectId", projectId);
			requestObject.map.put("code", code);
			requestObject.map.put("projectId", SPreferences.getData(mContext, "", "projectId").toString());

			String requestUrl = RequestBuilder.build(requestObject);

			try {
				IjConnect.doRequest(requestUrl, data);

				if (data.code == null) {
					mFailLog = getResources().getString(R.string.loaddata_exception);
				} else if (!data.code.equals(CommonData.RESULT_SUCCESS)) {
					mFailLog = data.msg;
				}

			} catch (Exception e) {
				mFailLog = getResources().getString(R.string.loaddata_exception);
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (!TextUtils.isEmpty(mFailLog)) { // showToast(mFailLog);
				dismissProgressDialog();
				showToast(mFailLog);
			} else {
				if (data.code != null && data.code.equals(CommonData.RESULT_SUCCESS)) {
					dismissProgressDialog();
					// startActivity(new Intent(MyInvestActivity.this,
					// ProjectDetailActivity.class));
					Intent intent = new Intent();
					intent.setClass(MyInvestActivity.this, ProjectDetailActivity.class);
					intent.putExtra("investProgress", data.investProgress);
					showToast(data.msg);
					setResult(RESULT_OK, intent);
					finish();

				}

			}
		}
	}

	public static class RedPacketViewHolder {
		private CheckedTextView text1;
	}

	private HandleCallBack mRedPacketHandleCallBack = new HandleCallBack() {

		@Override
		public void handle(int position, View convertView, ViewGroup parent, Object holder, Object item) {
			RedPacketInfo info = (RedPacketInfo) item;
			RedPacketViewHolder h = (RedPacketViewHolder) holder;
			String amount = "0";
			if (info != null && !TextUtils.isEmpty(info.amount)) {
				amount = info.amount;
			}
			h.text1.setText(getString(R.string.red_packet_usable_content, amount));
		}
	};

	public void showRedPacketDialog(final AppinvestDataClass dc) {
		if (redPacketDialog == null) {
			redPacketDialog = new RedPacketDialog(MyInvestActivity.this);
		}
		if (redPacketDialog.isShowing()) {
			redPacketDialog.dismiss();
		}
		redPacketDialog.setRedPacketMessage(dc.giftMoneyMessage);
		redPacketDialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				MyInvestActivity.mDialogFlag = true;
				ProjectDetailActivity.AppInvestDialgFlag = true;
				ProjectDetailActivity.AppInvestDialgProgress = dc.investProgress;
				Intent intent = new Intent();
				intent.putExtra("investProgress", dc.investProgress);
				MyInvestActivity.instance.setResult(Activity.RESULT_OK, intent);
				MyInvestActivity.instance.finish();
			}
		});
		redPacketDialog.show();
	}

	public void getUserRedPacketMessage(String demandId, double investAmount) {
		// 如果投资金额和上次的输入的金额不一样，并且不是体验标时，重新获取红包信息，注意体验标不使用红包
		if (investAmount != lastInvestAmount && !isNewerInvest) {
			lastInvestAmount = investAmount;
			new GetUserRedPacketMessageTask(demandId, investAmount).execute();
		}
	}

	class GetUserRedPacketMessageTask extends AsyncTask<Void, Void, String> {
		private String demandId;
		private double investAmount;
		private InvestUserRedPacketDataClass dc = new InvestUserRedPacketDataClass();

		public GetUserRedPacketMessageTask(String demandId, double investAmount) {
			this.demandId = demandId;
			this.investAmount = investAmount;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			investUserRedPacketData = null;
		}

		@Override
		protected String doInBackground(Void... arg0) {
			RequestObject reqObj = new RequestObject();
			reqObj.method = "queryUserGiftMoney";
			reqObj.map.put("demandId", demandId);
			reqObj.map.put("investAmount", investAmount);
			return requestDataAndGetErrorMsg(reqObj, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			dismissProgressDialog();
			if ("-1".equals(dc.code)) {
				loginWebview();
				return;
			}

			if (!TextUtils.isEmpty(result)) {
				showRedPacketAndExperience(null);
                mLlllGainMoney.setVisibility(View.GONE);
				clearCouponRateData();
				showToast("获取优惠卷信息失败!");
			} else {
				showRedPacketAndExperience(dc);
				if (dc.gainList != null && dc.gainList.size() > 0) {
					mLlllGainMoney.setVisibility(View.VISIBLE);

				} else {
					mLlllGainMoney.setVisibility(View.GONE);
                    clearCouponRateData();
				}
				gainCanUsestr = dc.gainCanUse;
                if(TextUtils.isEmpty(gainCanUsestr)) {
					mLlllGainMoney.setVisibility(View.GONE);
					clearCouponRateData();
				} else {
					try {
						gainCanUseD = Double.parseDouble(gainCanUsestr);
					} catch (Exception e) {
						gainCanUseD = 0;
					}
					if(gainCanUseD > 0) {
						mLlllGainMoney.setVisibility(View.VISIBLE);
						clearCouponRateData();
						mTvrateOfYearuse.setText("该项目可使用加息券");
					} else {
						mLlllGainMoney.setVisibility(View.GONE);
						clearCouponRateData();
					}
				}
			}
          calculateExpectedReturn();
		}

	}

	public SpannableStringBuilder showTotalAmount(String pre, String amount) {
		amount = "￥" + amount;
		SpannableStringBuilder experienceStyle = new SpannableStringBuilder(pre + amount + "元");
		int lenght = pre.length();
		experienceStyle.setSpan(new ForegroundColorSpan(0xffef8613), lenght, lenght + amount.length(),
				Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		return experienceStyle;
	}

	public void showRedPacketAndExperience(InvestUserRedPacketDataClass temp) {
		investUserRedPacketData = temp;
		String limitAmount = "";
		String totalAmount = "0.00";
		String experienceLimitAmount = "";
		String experienceAmount = "0.00";
		if (temp != null) {
			limitAmount = temp.giftMoneyLimitAmount;
			totalAmount = TextUtils.isEmpty(temp.giftMoney) ? "0.00" : temp.giftMoney;
			experienceLimitAmount = temp.experienceLimitAmount;
			experienceAmount = TextUtils.isEmpty(temp.experienceAmount) ? "0.00" : temp.experienceAmount;
		}

		redPacketTotalAmount.setText(showTotalAmount(getString(R.string.red_packet_total_amount), totalAmount));
		experienceTotalAmount.setText(showTotalAmount(getString(R.string.experience_total_amount), experienceAmount));

		if (TextUtils.isEmpty(limitAmount)) {
			redPacketUseLimitContainer.setVisibility(View.GONE);
			redPacketUseAmountLimit.setText("");
		} else {
			redPacketUseLimitContainer.setVisibility(View.VISIBLE);
			redPacketUseAmountLimit.setText(getString(R.string.red_packet_use_limit, limitAmount));
		}
		if (TextUtils.isEmpty(experienceLimitAmount)) {
			experienceUseLimitContainer.setVisibility(View.GONE);
			experienceUseAmountLimit.setText("");
		} else {
			experienceUseLimitContainer.setVisibility(View.VISIBLE);
			experienceUseAmountLimit.setText(getString(R.string.experience_use_limit, experienceLimitAmount));
		}

		if ((TextUtils.isEmpty(limitAmount) || AppUtil.moneyToNum(limitAmount) > 0)
				&& AppUtil.moneyToNum(totalAmount) > 0) {
			redPacketContainer.setVisibility(View.VISIBLE);
		} else {
			redPacketContainer.setVisibility(View.GONE);
			redPacketAmountInput.setText("");
		}

		if ((TextUtils.isEmpty(experienceLimitAmount) || AppUtil.moneyToNum(experienceLimitAmount) > 0)
				&& AppUtil.moneyToNum(experienceAmount) > 0) {
			experienceContainer.setVisibility(View.VISIBLE);
		} else {
			experienceContainer.setVisibility(View.GONE);
			experienceAmountInput.setText("");
		}
	}

	public class DotFilter implements InputFilter {

		String dot = ".";

		public DotFilter() {
			dot = ".";
		}

		@Override
		public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
			dot.contains(source);
			String temp = dest.toString();
			if (temp.contains(dot) && source.toString().contains(dot)) {
				return "";
			}
			return null;
		}

	}
        public void clearCouponRateData() {
			gainMoneyTradeIds = "";
			interestRateCouponlast = 0;
			interestRateCoupon = "";
			mSelect = -1;
		}
}
